<template>
  <div
    v-loading="loading"
    class="img-upload-box"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 0.6)"
  >
    <div v-for="(file,index) in fileList" :key="index" class="avatar-uploader">
      <el-image style="width: 100%;height: 100%" :src="file" fit="contain" :preview-src-list="fileList">
        <template #error>
          <img src="@/assets/file.png" alt="" fit="contain" style="width: 100%">
        </template>
      </el-image>
<!--      <el-link :href="file">下载</el-link>-->
      <i class="el-icon-error close-icon" @click="onClose(index)" />
    </div>
    <el-upload v-if="(multiple || !fileList.length) && !disabled" action="" class="avatar-uploader active" :before-upload="beforeUpload">
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <slot />
  </div>
</template>

<script>
import {http, uploadFile} from '@/api'
import Compressor from 'compressorjs'

export default {
  name: 'FileUpload',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      fileList: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.fileList = (val || '').split(',').filter(el => el)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    onClose(index) {
      this.fileList.splice(index, 1)
    },
    // 压缩图片
    compressImage(file) {
      return new Promise((resolve, reject) => {
        new Compressor(file, {
          quality: 0.8, // 图片质量，范围0-1
          maxWidth: 4096, // 最大宽度
          maxHeight: 4096, // 最大高度
          convertSize: 4000000, // 如果图片大于4MB，压缩到4MB以下
          success: (result) => {
            // 创建新的文件，保留原始文件名和类型
            const compressedFile = new File([result], file.name, {
              type: file.type,
              lastModified: Date.now()
            });
            resolve(compressedFile);
          },
          error: reject,
        })
      })
    },
    // 上传之前: 获取file对象进行参数验证
    async beforeUpload(file) {
      // 检查文件类型
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件')
        return false
      }

      try {
        this.loading = true
        // 压缩图片
        const compressedFile = await this.compressImage(file)
        console.log('compressedFile',compressedFile)

        // 检查压缩后的大小
        if (compressedFile.size / 1024 / 1024 > 5) {
          this.$message.error('压缩后文件仍超过5MB，请选择较小的图片')
          this.loading = false
          return false
        }

        // 上传压缩后的文件
        const res = await uploadFile(compressedFile)
        if (this.multiple) {
          this.fileList.push(res.data.url)
        } else {
          this.fileList = [res.data.url]
        }
        this.$emit('change', this.fileList.join(','))
      } catch (error) {
        console.error('图片处理失败:', error)
        this.$message.error('图片处理失败，请重试')
      } finally {
        this.loading = false
      }
      return false
    }
  }
}
</script>

<style lang="scss">
.file-upload-wrapper {
  display: flex;
  flex-wrap: wrap;
}
.img-upload-box {
  display: flex;
  flex-wrap: wrap;
  .el-upload-list {
    display: none;
  }
  .avatar-uploader {
    width: 98px;
    height: 98px;
    margin-right: 8px;
    margin-bottom: 8px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .close-icon {
      position: absolute;
      right: -8px;
      top: -8px;
      font-size: 24px;
      color: #0bc162;
      cursor: pointer;
    }
    &.active {
      cursor: pointer;
      .close-icon {
        display: none;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 98px;
    height: 98px;
    line-height: 100px !important;
    text-align: center;
  }
  .avatar {
    width: 98px;
    height: 98px;
    display: block;
  }
}
</style>
